package com.wanpinghui.wphlibrary.model.base;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;

import com.bumptech.glide.load.resource.bitmap.BitmapDecoder;
import com.wanpinghui.wphlibrary.common.IWPHApi;
import com.wanpinghui.wphlibrary.model.base.bean.ImageBean;
import com.yunshl.yunshllibrary.utils.LogUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit.Network;
import retrofit.callback.YRequestCallback;
import retrofit.callback.YunShlAction;
import retrofit.callback.YunShlResult;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/***
 * 功能描述:
 * 作者:qiujialiu
 * 时间:2017/12/1
 ***/

public class FileUploadManager {

    /**
     * 上传图片文件
     * @param filePath
     * @param callback
     */
    public static void uploadProductImage(String filePath, final YRequestCallback<ImageBean> callback) {
        File file = new File(filePath);
        if (!file.exists()) {
            if (callback != null) {
                callback.onFailed(0,"文件不存在，请检查是否开启存储权限");
            }
        }else {
            RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"),file))
                    .build();
            Network.getApi(IWPHApi.class)
                    .uploadProductFile(requestBody)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<YunShlResult<ImageBean>>() {
                        @Override
                        public void call(YunShlResult<ImageBean> result) {
                            LogUtils.w("FileUploadManager","图片上传成功:"+result.body.getUrl());
                            if (result.isSuccess()) {
                                if (callback != null) {
                                    callback.onSuccess(result.body);
                                }
                            }
                        }
                    }, new YunShlAction<Throwable>(callback));

        }
    }

    public static String bitmapToString(String filePath) {
        File file = new File(filePath);
        if (file.exists()) {
            try {
                byte[] data;
                FileInputStream inputStream = new FileInputStream(file);
                data = new byte[inputStream.available()];
                inputStream.read(data);
                return Base64.encodeToString(data, Base64.DEFAULT);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String bitmapToString2(String filePath) {
        try {
            Bitmap bm = decodeBitmap(filePath);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            //1.5M的压缩后在100Kb以内，测试得值,压缩后的大小=94486字节,压缩后的大小=74473字节
            //这里的JPEG 如果换成PNG，那么压缩的就有600kB这样
            bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            byte[] b = baos.toByteArray();
            return Base64.encodeToString(b, Base64.DEFAULT);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        return null;
    }

    public static Bitmap decodeBitmap(String path){
        Bitmap bitmap;
        try {
            bitmap =  BitmapFactory.decodeFile(path);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bitmap = decodeBitmap2(path,2);
        }
        return bitmap;
    }

    private static Bitmap decodeBitmap2(String path,int scale) {
        Bitmap bitmap;BitmapFactory.Options opts2 = new BitmapFactory.Options();
        opts2.inJustDecodeBounds = false;
        opts2.inSampleSize = scale;
        try {
            bitmap = BitmapFactory.decodeFile(path,opts2);
        } catch (OutOfMemoryError e) {
            return decodeBitmap2(path,scale+1);
        }
        return bitmap;
    }

}
